package com.gitee.zhangchenyan.takin.sys.init;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.gitee.zhangchenyan.takin.auth.AuthCheckPermissionParameter;
import com.gitee.zhangchenyan.takin.auth.AuthUserService;
import com.gitee.zhangchenyan.takin.cache.IJedisClient;
import com.gitee.zhangchenyan.takin.cache.JedisClient;
import com.gitee.zhangchenyan.takin.service.client.ServiceClient;
import com.gitee.zhangchenyan.takin.sys.entity.SysUser;
import com.gitee.zhangchenyan.takin.sys.service.ISysRolesMenusService;

import java.util.ArrayList;
import java.util.List;

/**
 * @Deacription takin获取当前用户所以权限
 * @Author zl
 * @Date 2022/4/10 21:51
 * @Version 1.0
 **/
@Component
public class AuthCheckPermissionParameterImpl implements AuthCheckPermissionParameter {
    private final AuthUserService authUserService;
    private final IJedisClient jedisClient;
    private final ISysRolesMenusService sysRolesMenusService = ServiceClient.create(ISysRolesMenusService.class);

    private final static String permissionKey = "takin_permission_";

    public AuthCheckPermissionParameterImpl(AuthUserService authUserService, JedisClient jedisClient) {
        this.authUserService = authUserService;
        this.jedisClient = jedisClient;
    }

    @Override
    public List<String> getPermissions() {
        String token = authUserService.getToken();
        String redisPermissionStr = jedisClient.get(permissionKey + token);
        if (StringUtils.hasLength(redisPermissionStr)) {
            return JSON.parseObject(redisPermissionStr, new TypeReference<ArrayList<String>>() {
            });
        }
        SysUser sysUser = authUserService.getUser(SysUser.class);
        List<String> permissions = sysRolesMenusService.getPermissionsByUserId(sysUser.getId());
        jedisClient.set(permissionKey + token, 7200L, JSON.toJSONString(permissions));
        return permissions;
    }
}
